import re

from loguru import logger

from com.arcfox.manager.redis_task_manager import RedisTaskManager
from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.school.processor.base_processor import BaseProcessor
from com.arcfox.util.muilty_coroutine_util import concurrency
from com.arcfox.util.redis_key_manager import HAND_UNIVERSITY_SCHOOL_LIST_KEY


class AqcProcessor:
    def __init__(self):
        self.task_manager = RedisTaskManager(HAND_UNIVERSITY_SCHOOL_LIST_KEY)

    async def parse_and_save_data(self, response):
        logger.info(response)
        tasks = []
        tasks.append(self.parse_detail_info(response))
        #await self.__save(tasks=tasks)

    def parse_detail_info(self, response):
        result_json = response.json()
        result_data = result_json['data']
        basic_data = result_data['basicData']
        try:
            basic_data.pop('entLogo')
            basic_data.pop('shareLogo')
            basic_data.pop('isClaim')
            basic_data.pop('claimUrl')
            basic_data.pop('isCollected')
            basic_data.pop('benchMark')
            basic_data.pop('personId')
            basic_data.pop('compNum')
            basic_data.pop('compNumLink')
            basic_data.pop('personLogo')
            basic_data.pop('personLogoWord')
            basic_data.pop('hideButton')
            basic_data.pop('insuranceInfo')
            basic_data.pop('personLink')
            basic_data.pop('districtCode')
            basic_data.pop('prinType')
        except Exception as e:
            pass
        directors_data = result_data['directorsData']
        shareholders_data = result_data['shareholdersData']
        return {"Basic": basic_data, "Partners": directors_data, "Employees": shareholders_data}

    @concurrency(5)
    async def __save(self, **params):
        task = params['task']
        mapping = db.MysqlMapping("tb_enrollment_plan")
        select_data = {
            "university_uid": task['university_uid'], "province_name": task['province_name'],
            "plan_year": task['plan_year'], "plan_batch": task['plan_batch'], "major_year": task['major_year'],
            "plan_category": task['plan_category'], "plan_major_name": task['plan_major_name']
        }
        if task['major_group']:
            select_data['major_group'] = task['major_group']
        old_data = await mapping.query(select_data, ["id"])
        if old_data:
            logger.info("{}数据已存在!{}", old_data[0][0], task)
        else:
            await mapping.insert(task)
